package com.example.hello.security;

import com.example.hello.entity.User;
import com.example.hello.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

  @Autowired
  private UserService userService;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userService.getUserByUsername(username);
    if (user == null) {
      throw new UsernameNotFoundException("用户不存在: " + username);
    }

    // 确保密码不为空
    if (user.getPassword() == null) {
      throw new UsernameNotFoundException("用户密码不存在: " + username);
    }

    List<SimpleGrantedAuthority> authorities = new ArrayList<>();
    // 添加角色，注意角色需要加上ROLE_前缀
    authorities.add(new SimpleGrantedAuthority("ROLE_" + user.getRole().toUpperCase()));

    return new org.springframework.security.core.userdetails.User(
        user.getUsername(),
        user.getPassword(),
        user.getStatus() == 1, // 状态为1表示启用
        true,
        true,
        true,
        authorities);
  }
  
  /**
   * 根据用户名获取用户ID
   * @param username 用户名
   * @return 用户ID
   */
  public Long getUserIdByUsername(String username) {
    User user = userService.getUserByUsername(username);
    if (user == null) {
      throw new UsernameNotFoundException("用户不存在: " + username);
    }
    return user.getUserId();
  }
}